package cn.tedu.controller;

import cn.tedu.common.vo.JsonResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Kiven
 */
@RestController
@RequestMapping("/cookieSession")
public class TestCookieSessionController {

    @GetMapping("add")
    public JsonResult testCookieSessionAdd(HttpSession httpSession, HttpServletRequest request, HttpServletResponse response){
        // 设置session
        httpSession.setAttribute("username","jx");

        // 设置cookie
        Cookie cookie = new Cookie("username","jx");
        cookie.setDomain("localhost");
        cookie.setMaxAge(10);
        response.addCookie(cookie);

        return JsonResult.success();
    }

    @GetMapping
    public JsonResult testCookieSession(
            HttpSession httpSession
            , HttpServletRequest request, HttpServletResponse response){
        // 获取cookie
        String cookie = request.getHeader("cookie");

        // 获取sessionId
        HttpSession session = request.getSession();
        String id = session.getId();
        System.out.println("sessionID:"+id);
        System.out.println("我是cookie:"+cookie);

        // 获得会话中的username
        String username = (String)httpSession.getAttribute("username");
        System.out.println(username);

        return JsonResult.success();
    }

}
